package cn.kai.pet.Consumer;

import cn.kai.basic.config.BussinessException;
import cn.kai.order.domain.OrderPetAcquisition;
import cn.kai.order.service.IOrderPetAcquisitionService;
import cn.kai.pet.domain.SearchMasterMsg;
import cn.kai.pet.service.ISearchMasterMsgService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(topic = "pethome_topic", consumerGroup = "pethome-producer-group")
public class RocketMQConsumer implements RocketMQListener<Long> {
    @Autowired
    private IOrderPetAcquisitionService orderPetAcquisitionService;

    @Autowired
    private ISearchMasterMsgService searchMasterMsgService;

    @Override
    public void onMessage(Long id) {
        //验证消息
        if (id == null){
            throw new BussinessException("消息异常");
        }
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionService.findById(id);
        if (orderPetAcquisition == null){
            throw new BussinessException("查无此单");
        }
        // 订单-1取消 0待处理 1已完成
        if(orderPetAcquisition.getState() != 1){
            //如果30s内没有完成订单，则取消订单，放回宠物池，并设置shopId=null
            //1.根据msgId去查找寻主信息
            Long msgId = orderPetAcquisition.getSearchMasterMsgId();
            SearchMasterMsg searchMasterMsg = searchMasterMsgService.findById(msgId);
            //2.判断是否有此条寻主讯息
            if (searchMasterMsg == null){
                throw new BussinessException("寻主消息不存在，请重新操作");
            }
            //3.设置寻主消息的shopId为null，把宠物信息放回宠物池
            searchMasterMsg.setShopId(null);
            searchMasterMsgService.update(searchMasterMsg);
            //@todo 记录取消日志
            System.out.println("订单完成超时，已取消订单！");
        }
        System.out.println("恭喜您，订单已完成！");

    }
}
